package com.springcloud.security;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.springcloud.commons.result.Result;
import com.springcloud.commons.utils.StringUtils;
import com.springcloud.jwt.JwtConfigProperty;
import com.springcloud.jwt.JwtUtil;
import com.springcloud.model.SysResource;
import com.springcloud.service.ISysResourceService;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 登陆成功调用,在这里生成JWT，缺点是过了设置的失效时间必须重新验证
 *
 * @author Administrator
 *
 */
@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Autowired
    private JwtConfigProperty jwtConfig;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    ISysResourceService resourceService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Value("${jwt.expirationMinute}")
    String expirationMinute;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        String authHeader = request.getHeader(this.jwtConfig.getHeader());
        String tokenHead = this.jwtConfig.getTokenHead();
        if (StringUtils.isBlank(authHeader)) {
//            String username = authentication.getName();
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            String auth = authorities.iterator().next().toString();
            List<String> authoritiesList = Arrays.asList(auth.split("/"));
            String userid =  authoritiesList.get(0);
            String roleids = authoritiesList.get(1);
            List<String> resultList= new ArrayList<>(Arrays.asList(roleids.split(",")));
            List<SysResource> resourceList = resourceService.selectResourceByRoleIds(resultList);//通过roleids查询所拥有资源

            if(resourceList!=null && resourceList.size()>0){
                StringBuffer sb = new StringBuffer();
                for(SysResource resource:resourceList){
                    sb.append(resource.getUrl()+",");
                }

                String urls = sb.toString().substring(0,sb.length()-1);
                stringRedisTemplate.opsForValue().set(userid,urls,Long.valueOf(expirationMinute)+1,TimeUnit.MINUTES); // 将资源信息存入redis,时间比jwt过期时间长一分钟，防止bug
            }

            //生成token并写入httpheader和cookie
            String token = jwtUtil.generateToken(userid);
            response.setHeader(this.jwtConfig.getHeader(), tokenHead + token);
            response.setContentType("text/html;charset=UTF-8");
            Cookie cookie = new Cookie(this.jwtConfig.getHeader(), tokenHead + token);
            response.addCookie(cookie);
            Result result = new Result();
            result.setMsg("登录成功！");
            ObjectMapper mapper = new ObjectMapper();
            String data = mapper.writeValueAsString(result);
            response.getWriter().write(data);
        }
    }

}
